package com.aaa.forum.controller;


import com.aaa.forum.common.AppResult;
import com.aaa.forum.common.ResultCode;
import com.aaa.forum.config.AppConfig;
import com.aaa.forum.model.History;
import com.aaa.forum.model.User;
import com.aaa.forum.services.IHistoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags = "历史记录接口")
@Slf4j
@RestController
@RequestMapping("/history")
public class HistoryController {

    @Resource
    private IHistoryService historyService;

    @ApiOperation("获取历史记录")
    @GetMapping("/getHistory")
    public AppResult<List<History>> getHistory(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        return AppResult.success(historyService.selectAllByUserId(user.getId()));
    }

    @ApiOperation("删除历史记录")
    @PostMapping("/delete")
    public AppResult deleteByList(HttpServletRequest request,
                                @ApiParam("历史记录id数组") @RequestBody List<Long> deleteArray) {
        // 获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        for (Long id : deleteArray) {
            // 获取历史记录信息
            History history = historyService.selectById(id);
            // 校验历史记录是否存在
            if (history == null || history.getDeleteState() == 1) {
                log.warn(ResultCode.FAILED_HISTORY_NOT_EXISTS.toString());
                return AppResult.failed(ResultCode.FAILED_HISTORY_NOT_EXISTS);
            }
            // 校验是否属于该用户
            if (history.getUserId() != user.getId()) {
                log.warn(ResultCode.FAILED_FORBIDDEN.toString());
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            // 调用service
            historyService.delete(id);
        }
        return AppResult.success();
    }
}
